//
//  StepViewController.m
//  LineByLine
//
//  Created by 병철 김 on 11. 11. 12..
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "StepViewController.h"
#import "StudyManager.h"
#import "ReadingViewController.h"
#import "WritingViewController.h"

#define kStep1Reading 1
#define kStep2Listening 2
#define kStep3Speaking 3
#define kStep4Writing 4
#define kStep2_2ListeningAll 5
#define kStep3_2SpeakingAll 6

@interface StepViewController(Private)
- (void) loadToolBars;
- (id) getCurrentSentence;
- (BOOL) moveNext;
- (void) finishRecordAll;
@end

@implementation StepViewController
@synthesize book, curPage, step;
@dynamic stepView;

- (void)dealloc {
    [self finishRecordAll];
    [book release];
    [step release];
    [super dealloc];
}

- (void) loadToolBars {
    UIBarButtonItem *flexWidth = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    NSMutableArray *toolBarItems = [[NSMutableArray alloc] initWithCapacity:5];
    
    switch ([self.step intValue]) {
        case kStep1Reading : {
            UIBarButtonItem *playButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPlay target:self action:@selector(onClickPlay)];
            [toolBarItems addObject:flexWidth];
            [toolBarItems addObject:playButton];
            [toolBarItems addObject:flexWidth];            
            [playButton release];
        }
            break;
        case kStep2Listening : {
        }
            break;
        case kStep3Speaking : {
            recordButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCamera target:self action:@selector(onClickRecord)];
            UIBarButtonItem *playRecordButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(onClickPlayRecord)];
            
            [toolBarItems addObject:flexWidth];
            [toolBarItems addObject:recordButton];
            [toolBarItems addObject:playRecordButton];
            [toolBarItems addObject:flexWidth];
            
            [recordButton release];
            [playRecordButton release];
        }
            break;
        case kStep4Writing : {
        
        }
            break;
        case kStep3_2SpeakingAll : {
            UIBarButtonItem *recordAllButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCamera target:self action:@selector(onClickRecordAll)];
            
            [toolBarItems addObject:flexWidth];
            [toolBarItems addObject:recordAllButton];
            [toolBarItems addObject:flexWidth];
            
            [recordAllButton release];
        }
            break;
        default:
            break;
    }
    
    [self setToolbarItems:toolBarItems];
    [toolBarItems release];
    [flexWidth release];
}

- (void)loadView {
    [super loadView];
    [self loadToolBars];
    
    offset = [[book valueForKey:@"offset"] intValue] / 1000;
    curPage = [[[StudyManager sharedStudyManager] pageOfBook:book step:self.step] intValue];
    [self configView];
    [self.stepView setCurPage:curPage];
    [self.stepView configView];
}

- (void) configView {}

- (void)viewWillAppear:(BOOL)animated {
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
    [self.navigationController setNavigationBarHidden:YES];
    [self.navigationController setToolbarHidden:NO];
    [self.navigationController.toolbar setBarStyle:UIBarStyleBlackOpaque];
    
    if ([self hasMedia]) {
        BOOL isSuccess = [[AudioManager sharedAudioManager] prepareBook:book];
        [[AudioManager sharedAudioManager] setAudioDelegate:self];
        if (!isSuccess) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error" message:@"음악 파일 초기화 에러" delegate:nil cancelButtonTitle:@"확인" otherButtonTitles:nil];
            [alertView show];
            [alertView release];
        }
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
    [self.navigationController.navigationBar setBarStyle:UIBarStyleDefault];
    [self.navigationController setNavigationBarHidden:NO];
    [self.navigationController setToolbarHidden:YES];
    
    if ([self hasMedia]) {
        [[AudioManager sharedAudioManager] closePlayer];
    }
}

- (BOOL) hasMedia {
    NSString *media = [book valueForKey:@"media"];
    return media != nil && [media length] > 0;
}

#pragma mark - private method
- (id) getCurrentSentence {
    PairTableViewCell *cell = (PairTableViewCell*) [self.stepView getCurrentCell];
    if (cell) {
        id sentence = [cell sentence];
        return sentence;
    }
    return nil;
}

- (BOOL) moveNext {
    return [self.stepView moveNext];
}

- (void) finishRecordAll {
    isRecordingAll = NO;
    if (timer) {
        [timer invalidate];
        [timer release];
    }
    timer = nil;
}

#pragma mark - StepView delegate
- (void)didChangePage:(NSInteger)page {
    curPage = page;
    [[StudyManager sharedStudyManager] setBook:[self book] step:[self step] currentPage:[NSNumber numberWithInt:page]];
}

#pragma mark - toolbar event handler
- (void) onClickBookmark {
    [self finishRecordAll];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void) onClickPlay {
    id sentence = [self getCurrentSentence];
    float start = [[sentence valueForKey:@"start"] floatValue];
    float duration = [[sentence valueForKey:@"duration"] floatValue];
    [[AudioManager sharedAudioManager] playBookStart:(offset + start) duration:duration];
}

- (void) onClickRecord {
    [[AudioManager sharedAudioManager] recordBookPage:self.curPage];
}

- (void) onClickPlayRecord {
    [[AudioManager sharedAudioManager] playRecordBookPage:self.curPage];
}

- (void) onClickRecordAll {
    isRecordingAll = YES;
    status = kWait;
    waitCount = 10;
    nextStatus = kPlayStart;
    
    timer = [[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(recordAllLoop) userInfo:nil repeats:YES] retain];;
}

- (void) recordAllLoop {
//    if (!isRecordingAll) {
//        [timer invalidate];
//        [timer release];
//        timer = nil;
//    }
    switch (status) {
        case kWait : {
            waitCount--;
            if (waitCount <= 0) {
                status = nextStatus;
            }
        }
            break;
        case kPlayStart : {
            NSLog(@"play start");
            [self onClickPlay];
            status = kWait;
            nextStatus = kWait;
            waitCount = 300;
        }
            break;
        case kPlayFinished : {
            [[AudioManager sharedAudioManager] playBeep];
            status = kRecordStart;
        }
            break;
        case kRecordStart : {
            NSLog(@"record start");
            [self onClickRecord];
            status = kWait;
            nextStatus = kWait;
            waitCount = 300;
        }
            break;
        case kRecordFinished : {
            [[AudioManager sharedAudioManager] playBeep];
            status = kWait;
            nextStatus = kPlayRecordStart;
            waitCount = 10;
        }
            break;
        case kPlayRecordStart : {
            NSLog(@"play record start");
            [self onClickPlayRecord];
            status = kWait;
            nextStatus = kWait;
            waitCount = 300;
        }
            break;
        case kPlayRecordFinished : {
            [[AudioManager sharedAudioManager] playBeep];
            status = kAskRetry;
        }
            break;
        case kAskRetry : {
            NSLog(@"ask retry");
            [[AudioManager sharedAudioManager] askRetry];
            status = kWait;
            nextStatus = kWait;
            waitCount = 200;
        }
            break;
        case kRetry : {
            NSLog(@"retry");
            status = kPlayStart;
        }
            break;
        case kNext : {
            NSLog(@"next");
            if ([self moveNext]) {
                [[AudioManager sharedAudioManager] playBeep];
                status = kPlayStart;
            } else {
                // 여기서, 전체 녹음 재생하거나, 다시 처음부터 녹음하거나
                [self finishRecordAll];
            }
            break;
        }
        default:
            break;
    }

}

#pragma mark - AudioManagerDelegate
- (void) didFinishPlaying {
    status = kWait;
    nextStatus = kPlayFinished;
    waitCount = 10;
}

- (void) didFinishRecording {
    status = kRecordFinished;
}

- (void) didFinishPlayRecord {
    status = kWait;
    nextStatus = kPlayRecordFinished;
    waitCount = 5;
}

- (void) didFinishRetry:(BOOL)retry {
    if (retry) {
        status = kRetry;
    } else {
        status = kNext;
    }
}
@end
